import Footer from '@/components/Footer';
import {LockOutlined, MobileOutlined, UserOutlined,} from '@ant-design/icons';
import {LoginForm, ProFormCaptcha, ProFormText,} from '@ant-design/pro-components';
import {history, Link, useModel} from '@umijs/max';
import {Alert, message, Tabs} from 'antd';
import React, {useState} from 'react';
import styles from './index.less';
import {emailCodeUsingGet, userLoginByEmailUsingPost, userLoginUsingPost} from "@/services/backend/userController";


const LoginMessage: React.FC<{
  content: string;
}> = ({content}) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};
const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
  const [type, setType] = useState<string>('account');

  // @ts-ignore
  const {initialState, setInitialState} = useModel('@@initialState');

  const handleSubmit = async (values: API.UserLoginRequest) => {
    try {
      setUserLoginState((preState) => ({...preState, status: 'loading'}));
      let res: { data?: any } = { data: undefined };
      if (type === 'account') {
        // 登录
        res = await userLoginUsingPost({
          ...values,
        });
      } else {
        res = await userLoginByEmailUsingPost({
          ...values,
        });
      }
      if (res.data) {
        const { userRole } = res.data;
        const urlParams = new URL(window.location.href).searchParams;
        //用户跳转首页
        let redirectUrl = urlParams.get('redirect') || '/';
        //管理员跳转管理界面
        if (userRole === 'admin') {
          redirectUrl = '/admin/borrow-record-manage';
        }
        setTimeout(() => {
          history.push(redirectUrl);
        }, 100);
        setInitialState({
          loginUser: res.data
        });
        return;
      }
    } catch (error) {
      const defaultLoginFailureMessage = '登录失败!';
      message.error(defaultLoginFailureMessage);
    }
  }

  const {status, type: loginType} = userLoginState;
  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <LoginForm
          logo={<img alt="logo" src="/logo.svg"/>}
          title="图书管理系统"
          subTitle={'登录'}
          initialValues={{
            autoLogin: true,
          }}
          /*          actions={[
                      '其他登录方式 :',
                      <AlipayCircleOutlined key="AlipayCircleOutlined" className={styles.icon} />,
                      <TaobaoCircleOutlined key="TaobaoCircleOutlined" className={styles.icon} />,
                      <WeiboCircleOutlined key="WeiboCircleOutlined" className={styles.icon} />,
                    ]}*/
          onFinish={async (values) => {
            await handleSubmit(values as API.UserLoginRequest);
          }}
        >
          <Tabs
            activeKey={type}
            onChange={setType}
            centered
            items={[
              {
                key: 'account',
                label: '账户密码登录',
              },
              {
                key: 'email',
                label: '邮箱登录',
              },
            ]}
          />

          {status === 'error' && loginType === 'account' && (
            <LoginMessage content={'错误的用户名和密码'}/>
          )}
          {type === 'account' && (
            <>
              <ProFormText
                name="userAccount"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={styles.prefixIcon}/>,
                }}
                placeholder={'用户名: '}
                rules={[
                  {
                    required: true,
                    message: '用户名是必填项！',
                  },
                ]}
              />
              <ProFormText.Password
                name="userPassword"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon}/>,
                }}
                placeholder={'密码: '}
                rules={[
                  {
                    required: true,
                    message: '密码是必填项！',
                  },
                ]}
              />
            </>
          )}

          {status === 'error' && loginType === 'email' && <LoginMessage content="验证码错误"/>}
          {type === 'email' && (
            <>
              <ProFormText
                fieldProps={{
                  size: 'large',
                  prefix: <MobileOutlined className={styles.prefixIcon}/>,
                }}
                name="email"
                placeholder={'请输入邮箱！'}
                rules={[
                  {
                    required: true,
                    message: '邮箱是必填项！',
                  },
                  {
                    // pattern: /^1\d{10}$/,
                    pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/,
                    message: '不合法的邮箱！',
                  },
                ]}
              />
              <ProFormCaptcha
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon}/>,
                }}
                captchaProps={{
                  size: 'large',
                }}
                placeholder={'请输入验证码！'}
                captchaTextRender={(timing, count) => {
                  if (timing) {
                    return `${count} ${'秒后重新获取'}`;
                  }
                  return '获取验证码';
                }}
                name="code"
                phoneName="email"
                rules={[
                  {
                    required: true,
                    message: '验证码是必填项！',
                  },
                ]}
                onGetCaptcha={async (email) => {
                   // 将 email 赋值给一个变量
                  const result = await emailCodeUsingGet({
                    email: email,
                  });
                  if (result.data === false) {
                    return;
                  }
                  message.success('获取验证码成功！3分钟有效');
                }}
              />
            </>
          )}
          <div
            style={{
              marginBottom: 24,
            }}
          >

            <Link to="/user/register">新用户注册</Link>
            {/*<a
              style={{
                float: 'right',
              }}
            >
              <Link to="/user/login">忘记密码? 邮箱登录</Link>
            </a>*/}
          </div>
        </LoginForm>
      </div>
      <Footer/>
    </div>
  );
};
export default Login;
